class LinkNode {
  constructor(val, next) {
    this.val = val;
    this.next = next;
  }
}

class MyLinkedList {
  constructor() {
    this.tail = null;
    this.head = null;
    this.length = 0;
  }
  /**
  * @param {number} index
  * @return {number}
  */
  get(index) {
    //如果索引大于链表长度
    if (index > this.length - 1) {
      return -1;
    }
    let ptr = this.head;
    while (index--) {
      ptr = ptr.next;
    }
    return ptr.val;
  }
  /**
  * @param {number} val
  * @return {void}
  */
  addAtHead(val) {
    //建立新增节点
    let node = new LinkNode(val, this.head);
    this.head = node;
    //当链表中无节点时
    if (this.length === 0) {
      this.tail = node;
    }
    this.length++;
  }
  /**
  * @param {number} val
  * @return {void}
  */
  addAtTail(val) {
    //建立新增节点
    let node = new LinkNode(val, null);
    //当链表中无节点时
    if (this.length === 0) {
      this.head = node;
    }

    //有节点时
    else {
      this.tail.next = node;
    }
    this.tail = node;
    this.length++;
  }
  /**
  * @param {number} index
  * @param {number} val
  * @return {void}
  */
  addAtIndex(index, val) {
    //如果索引大于链表长度
    if (index > this.length) {
      return;
    }
    //当在头部添加时
    if (index === 0) {
      //直接调用
      this.addAtHead(val);
      return;
    }
    //在尾部添加时
    if (index === this.length) {
      this.addAtTail(val);
      return;
    }
    //其他情况
    //ptr指向插入位置的前一位
    index = index - 1;
    let ptr = this.head;
    //从this.head头结点开始,移动ptr;让ptr指向插入位置的前一个结点.
    while (index--) {
      ptr = ptr.next;
    }
    // 新建节点，让它指向插入位置的值
    let node = new LinkNode(val, ptr.next);
    ptr.next = node;
    this.length++;
  }
  /**
  * @param {number} index
  * @return {void}
  */
  deleteAtIndex(index) {
    //如果索引大于链表长度
    if (index > this.length - 1 || index < 0) {
      return;
    }
    // 如果index为0，head向后移动一位
    if (index === 0) {
      this.head = this.head.next;
      //如果删除的也是尾节点
      if (index === this.length - 1) {
        this.tail = this.head;
      }
      this.length--;
      return;
    }

    let id = index;
    //ptr指向插入位置的前一位
    index = index - 1;
    let ptr = this.head;
    while (index--) {
      ptr = ptr.next;
    }
    ptr.next = ptr.next.next;
    //删除最后一位
    if (id === this.length - 1) {
      this.tail = ptr;
    }

    this.length--;
  }
}






var obj = new MyLinkedList()
var param_1 = obj.get(2)
obj.addAtHead(2)
obj.addAtIndex(1, 7)
obj.addAtIndex(2, 8)
obj.addAtIndex(3, 9)
obj.addAtTail(3)
// obj.deleteAtIndex(2)
console.log(obj.get(0))
console.log(obj.get(1))
console.log(obj.get(2))
console.log(obj.get(3))
console.log(obj.get(4))
console.log(obj);


/**
* Your MyLinkedList object will be instantiated and called as such:
* var obj = new MyLinkedList()
* var param_1 = obj.get(index)
* obj.addAtHead(val)
* obj.addAtTail(val)
* obj.addAtIndex(index,val)
* obj.deleteAtIndex(index)
*/
